package znbkCNtxl.CNTXL_TLTK;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.BaseRecyclerAdapter;
import com.example.znbk.znbklibrary.base.BaseRecyclerViewHolder;
import com.example.znbk.znbklibrary.util.LancooUtils;
import com.example.znbk.znbklibrary.widget.CustomEditText;
import com.example.znbk.znbklibrary.widget.ScaleButton;
import com.lancoo.znbkxx.R;
import com.tt.CoreType;
import com.tt.QType;
import com.tt.SkEgnManager;
import com.tt.listener.OnRecordListener;
import com.tt.widget.AudioRecoderUtils;
import com.tt.widget.JSONTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;

import znbkCNtxl.GetNtxlJson.CNtxlPaperEntity;

public class CNtxlTltkAnswerAdapter extends BaseRecyclerAdapter {

    private int TotalItemCount = -1;
    private void getAnswerInfor(){
        int SubmitState = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
        int Size = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).
                getSubChildList().get(0).getSubChildItem().size();
        if (SubmitState == 0) {
            for (int i = 0; i < Size; i++) {
                CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).
                        getSubChildList().get(0).getSubChildItem().get(i).setStuAnswer("");
            }
        }
        TotalItemCount = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getTotalItemCount();
    }


    private Context context;
    private List<CNtxlPaperEntity> CNtxlPaperEntity;
    private int quesIndex = -1;
    private boolean isVideoPlayEnd = false;
    private boolean isCouldRecordEnter = false;
    private LayoutInflater inflater;

    public CNtxlTltkAnswerAdapter(Context context, List<CNtxlPaperEntity> CNtxlPaperEntity, int quesIndex, boolean isVideoPlayEnd){
        this. context=context;
        this.CNtxlPaperEntity = CNtxlPaperEntity;
        this.quesIndex = quesIndex;
        this.isVideoPlayEnd  =isVideoPlayEnd;
        inflater=LayoutInflater. from(context);
        getAnswerInfor();
    }

    @Override
    public int getItemCount() {
        return TotalItemCount;
    }

    @Override
    public long getItemId(int position){
        return position;
    }

    private int RecordPosition = -1;
    private LinearLayout mLlOption;
    private TextView mTvQuesNumber;
    private CustomEditText mCedtWriteAnswer;
    private ScaleButton mSBtnRecordAnswer;
    @Override
    public View getHolderView(ViewGroup parent, int position) {
        View view = inflater.inflate(R.layout.cntxl_adapter_item_answer_tltk,parent, false);
        return view;
    }

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder baseRecyclerViewHolder, final int position) {
        mLlOption = baseRecyclerViewHolder.getView(R.id.ll_option);
        //显示小题题号
        int SortIndex =  CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getChildList().
                get(0).getSubChildList().get(0).getSubChildItem().get(position).getSortIndex();
        mTvQuesNumber = baseRecyclerViewHolder.getView(R.id.tv_quesNumber);
        mTvQuesNumber.setText(String.valueOf(SortIndex)+"、");

        //显示输入框内容（包括对错判断）
        mCedtWriteAnswer = baseRecyclerViewHolder.getView(R.id.cedt_writeAnswer);
        mCedtWriteAnswer.clearFocus();
        int SubmitState =  CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
        if(SubmitState==0||SubmitState==2){
            mCedtWriteAnswer.setFocusable(false);
        }else{
            mCedtWriteAnswer.setFocusable(true);
        }
        mCedtWriteAnswer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e("=afterTextChanged==",position+"=====================afterTextChanged======================"+s.toString());
                String stuAnswer = s.toString().trim();
                int SubmitState =  CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
                if(SubmitState!=2) {
                    CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                            get(0).getSubChildList().get(0).getSubChildItem().get(position).setStuAnswer(stuAnswer);
                }
            }
        });



        if(SubmitState==2){
            String StuAnswer =  CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                    get(0).getSubChildList().get(0).getSubChildItem().get(position).getStuAnswer();
            String ItemAnswer = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                    get(0).getSubChildList().get(0).getSubChildItem().get(position).getItemAnswer().trim();
            String[] ItemAnswerArray = LancooUtils.returnArray(ItemAnswer,"$/",2);
            List<String> list=Arrays.asList(ItemAnswerArray);
            if(list.contains(StuAnswer)){
                mCedtWriteAnswer.setText(StuAnswer);
                mCedtWriteAnswer.setTextColor(Color.parseColor("#00b30d"));
                // 使用代码设置drawableleft
                Drawable drawableRight = context.getResources().getDrawable(R.mipmap.image_tk_result_right);
                // / 这一步必须要做,否则不会显示.
                drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),drawableRight.getMinimumHeight());
                mCedtWriteAnswer.setCompoundDrawables(null,null,drawableRight,null);
            }else{
                ItemAnswer = ItemAnswer.replaceAll("\\$","");
                if(StuAnswer.equals("")){
                    Log.e("==SubmitStateAA11==","==编号=="+position+"==========StuAnswer==SSSSS=========="+StuAnswer);
//                    mCedtWriteAnswer.setText("未作答"+"("+ItemAnswer+")");
                    mCedtWriteAnswer.setText(Html.fromHtml(context.getResources().
                            getString(R.string.studentanswer_and_itemanswer,"未作答",ItemAnswer)));
                }else{
//                    mCedtWriteAnswer.setText(StuAnswer+"("+ItemAnswer+")");
                    mCedtWriteAnswer.setText(Html.fromHtml(context.getResources().
                            getString(R.string.studentanswer_and_itemanswer,StuAnswer,ItemAnswer)));
                }
                // 使用代码设置drawableleft
                Drawable drawableRight = context.getResources().getDrawable(R.mipmap.image_tk_result_wrong);
                // / 这一步必须要做,否则不会显示.
                drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),drawableRight.getMinimumHeight());
                mCedtWriteAnswer.setCompoundDrawables(null,null,drawableRight,null);
            }
        }else{
            mCedtWriteAnswer.setText(CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).
                    getSubChildList().get(0).getSubChildItem().get(position).getStuAnswer());
            mCedtWriteAnswer.setCompoundDrawables(null,null,null,null);
        }

        if(position==TotalItemCount-1){
            mLlOption.removeAllViews();
            if(SubmitState==0) {
                View mView = new View(context);
                mView.setBackgroundColor(Color.parseColor("#ffffff"));
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 300);
                mLlOption.addView(mView, lp);
            }else{
                View mView = new View(context);
                mView.setBackgroundColor(Color.parseColor("#ffffff"));
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 200);
                mLlOption.addView(mView, lp);
            }
        }

        //实现语音输入
        mSBtnRecordAnswer = baseRecyclerViewHolder.getView(R.id.sbtn_recordAnswer);
        if(isVideoPlayEnd){
            if(SubmitState==2){
                mSBtnRecordAnswer.setBackgroundResource(R.mipmap.button_record_dark);
                isCouldRecordEnter = false;
            }else{
                mSBtnRecordAnswer.setBackgroundResource(R.mipmap.button_record_light);
                isCouldRecordEnter = true;
            }
        }else{
            mSBtnRecordAnswer.setBackgroundResource(R.mipmap.button_record_dark);
            isCouldRecordEnter = false;
        }


        mSBtnRecordAnswer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if(isCouldRecordEnter){
                            Log.e("mSBtnRecordAnswer", "===============点击了==============" + position);
                            mRecoderUtils = new AudioRecoderUtils();
                            SkEgnManager.getInstance(context).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                            mRecoderUtils.startRecord();
                            RecordPosition = position;
                        }
                        return true;
                    case MotionEvent.ACTION_UP:
                        if(isCouldRecordEnter) {
                            SkEgnManager.getInstance(context).stopRecord();
                            mRecoderUtils.stopRecord();
                        }
                        return true;
                    case MotionEvent.ACTION_CANCEL:
                        if(isCouldRecordEnter) {
                            SkEgnManager.getInstance(context).stopRecord();
                            mRecoderUtils.stopRecord();
                        }
                        return true;
                }
                return false;
            }
        });

    }

    /********************************************************/
    private AudioRecoderUtils mRecoderUtils;
    private String  mCoreType = CoreType.EN_ASR_REC;
    /*
     * 话咪录音操作
     * */
    OnRecordListener mOnRecordListener = new OnRecordListener() {
        @Override
        public void onRecordStart() {
            //开始录制
//            Log.e("==onRecordingAA==","========vad_status==========="+"121212121212");
        }
        @Override
        public void onRecording(int vad_status, int sound_intensity) {
            //录制中
            int SubmitState = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
            if(SubmitState==2){
                SkEgnManager.getInstance(context).stopRecord();
                mRecoderUtils.stopRecord();
            }
            Log.e("==onRecordingAA==","========vad_status==========="+vad_status);
            Log.e("==onRecordingBB==","=========sound_intensity==========="+sound_intensity);
            if(vad_status==2){
                SkEgnManager.getInstance(context).stopRecord();
                mRecoderUtils.stopRecord();
            }
        }
        @Override
        public void onRecordEnd(String result) {
            //录制结束
            try {
                final JSONObject json = new JSONObject(result);
                Log.e("17kouyuAAA", "返回json===>" + result);
                String speakResult = "";
                if(!getResult(result).equals("")) {
                    speakResult = getResult(result);
                }
                Log.e("==AFGAFGG==","========VVVVVVKKKKK》》==========="+speakResult);
                if(!speakResult.equals("")) {
                    CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).getSubChildList().get(0).
                            getSubChildItem().get(RecordPosition).setStuAnswer(speakResult);

                    doRefresh(RecordPosition);
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };


    private String getResult(String result) {

        String choiceSoundResult = "";
        StringBuilder keyValue = new StringBuilder();
        try{
            JSONObject returnObj = new JSONObject(result);
            JSONObject resultJSONObject = returnObj.getJSONObject("result");
            if(resultJSONObject.has("overall")){
                keyValue.append("总    分: " + resultJSONObject.getString("overall") + "\n");
            }
            Log.e("getResultAAAAA", "====返回json========答案=========>" + resultJSONObject.getString("recognition"));
            choiceSoundResult = resultJSONObject.getString("recognition");

        }catch (Exception e){
            e.printStackTrace();
        }
        keyValue.append("\n");
        keyValue.append(JSONTool.stringToJSON(result));

        return choiceSoundResult;
    }
    /************************************************************/

    public void doRefresh(int position) {
        RecordPosition = position;
        notifyDataSetChanged();
    }

}